import json
import requests
from datetime import datetime

import streamlit as st


def get_data_by_id(record_id):
    json_data = {
        "record_id": record_id
    }
    data = {
        "json_data_str": json.dumps(json_data, ensure_ascii=False)
    }
    resp = requests.get(
        "http://127.0.0.1:8001/get_interview_records_by_record_id",
        data=data,
        timeout=60,
    )
    if resp.ok:
        result_dict = resp.json()
        data_dict = result_dict.get("data", {})
        return data_dict
    else:
        st.error(f"提交失败：{resp.status_code} {resp.text}")


def page_detail():
    if st.button("← 返回主界面"):
        st.session_state.update({"page": "page_main"})
        st.rerun()
    st.title("面试评价详情页")

    record_id = st.session_state.get("record_id", "")
    # print(record_id)
    data_dict = get_data_by_id(record_id)
    def parse_dt(v):
        if isinstance(v, datetime):
            return v
        if isinstance(v, str):
            try:
                return datetime.fromisoformat(v.replace("Z", "+00:00"))
            except:
                return None
        return None
    s = parse_dt(data_dict.get('process_start_time'))
    e = parse_dt(data_dict.get('process_end_time'))
    duration_str = ""
    if s and e:
        seconds = int((e - s).total_seconds())
        duration_str = f"{seconds // 60}分{seconds % 60}秒"
    st.write(f"开始时间：{data_dict.get('process_start_time', '')}")
    st.write(f"结束时间：{data_dict.get('process_end_time', '')}")
    st.write(f"处理耗时：{duration_str}")
    persona_tags_raw = data_dict.get('persona_tags', '')
    try:
        import ast
        persona_tags = ast.literal_eval(persona_tags_raw) if isinstance(persona_tags_raw, str) else []
    except Exception:
        persona_tags = []
    if persona_tags:
        st.subheader("画像标签")
        st.write(", ".join(persona_tags))
    tpl_key = data_dict.get('scoring_template_key', '')
    if tpl_key:
        st.subheader("评分模板")
        st.write(tpl_key)
        try:
            resp = requests.get(f"http://127.0.0.1:8001/scoring_template/list", timeout=10)
            items = resp.json().get("data", []) if resp.ok else []
            weights_json = ''
            for it in items:
                if it.get('template_key','') == tpl_key:
                    weights_json = it.get('weights_json','')
                    break
            if weights_json:
                st.caption(f"权重：{weights_json}")
        except Exception:
            pass
    col1, col2 = st.columns(2)
    with col1:
        disabled = data_dict.get('processing_status') == 1
        if st.button("删除录音", disabled=disabled):
            st.session_state['detail_confirm'] = {'type': 'recording', 'id': record_id}
        if st.session_state.get('detail_confirm', {}).get('type') == 'recording' and st.session_state['detail_confirm'].get('id') == record_id:
            st.warning(f"将删除 {data_dict.get('name','')}（{data_dict.get('company_name','')}，{str(data_dict.get('interview_time',''))[:19]}） 的录音文件，操作不可恢复。请确认是否继续。")
            cc1, cc2 = st.columns(2)
            with cc1:
                if st.button("确认删除录音"):
                    try:
                        payload = {"record_id": record_id}
                        data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                        resp = requests.post("http://127.0.0.1:8001/delete_recording", data=data, timeout=20)
                        result = resp.json()
                        if resp.ok and result.get("data") == "ok":
                            st.session_state.pop('detail_confirm', None)
                            st.success("录音已删除")
                            st.rerun()
                        else:
                            st.error(result.get("error", "删除失败"))
                    except Exception as e:
                        st.error(f"删除失败：{e}")
            with cc2:
                if st.button("取消"):
                    st.session_state.pop('detail_confirm', None)
    with col2:
        disabled = data_dict.get('processing_status') == 1
        if st.button("删除该记录", disabled=disabled):
            st.session_state['detail_confirm'] = {'type': 'record', 'id': record_id}
        if st.session_state.get('detail_confirm', {}).get('type') == 'record' and st.session_state['detail_confirm'].get('id') == record_id:
            st.warning(f"将删除 {data_dict.get('name','')}（{data_dict.get('company_name','')}，{str(data_dict.get('interview_time',''))[:19]}） 的整条记录（含所有详情与录音），操作不可恢复。请确认是否继续。")
            cc3, cc4 = st.columns(2)
            with cc3:
                if st.button("确认删除记录"):
                    try:
                        payload = {"record_id": record_id}
                        data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                        resp = requests.post("http://127.0.0.1:8001/delete_record", data=data, timeout=20)
                        result = resp.json()
                        if resp.ok and result.get("data") == "ok":
                            st.session_state.pop('detail_confirm', None)
                            st.success("记录已删除")
                            st.session_state.update({"page": "page_main"})
                            st.rerun()
                        else:
                            st.error(result.get("error", "删除失败"))
                    except Exception as e:
                        st.error(f"删除失败：{e}")
            with cc4:
                if st.button("取消"):
                    st.session_state.pop('detail_confirm', None)
    st.download_button(
        "下载md文件",
        data=str(data_dict['markdown_text']),
        file_name=f"{data_dict['interview_time'][:10]}_{data_dict['name']}_{data_dict['company_name']}_面试评价.md",
        mime="text/markdown",
    )
    st.markdown(str(data_dict['markdown_text']))
